package com.zookeeper.demo;

import com.zookeeper.utils.ConnectionUtil;
import org.apache.zookeeper.*;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Author 咕唧
 * @Date 2022/7/1 19:45
 * @Version 1.0
 */
public class ZookeeperWatcher03 implements Watcher {

    private static ZooKeeper zooKeeper;
    //阻塞时使用，参数表示需要放行的次数
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static String path = "/java";


    public static void main(String[] args) throws Exception {
        ZookeeperWatcher03 watcher03 = new ZookeeperWatcher03();
        //连接zookeeper
        zooKeeper = new ZooKeeper(ConnectionUtil.SERVER_ADDRESS, 10000, watcher03);
        countDownLatch.await();
        //创建节点
        watcher03.createPath(path, "ceshishuju");

//        // 读取数据
//        String data = watcher03.readData(path, true);
//        System.out.println(data);
//
//        //写入数据
//        watcher03.writeData(path, "xierudeshuju");
//
//        //我们获取了子节点,并且期望监听,肯定是子节点发生变化
//        List<String> children = watcher03.getChildren(path, true);
//        //遍历子节点
//        children.forEach(child -> {
//            String s = path + child;
//            byte[] data1 = new byte[0];
//            try {
//                data1 = zooKeeper.getData(s, true, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            System.out.println(new String(data1));
//        });
//        //创建一个子节点
//        watcher03.createChildren("/java/11", "随便写个数据");
        System.in.read();
        System.err.println("程序结束结束了");
    }

    /**
     * 创建节点
     *
     * @param path
     * @param data
     * @throws Exception
     */
    public void createPath(String path, String data) throws Exception {
        //提前声明说我要监听这个节点,true就是监听这个节点,如果这个节点在我们设置监听的时候还不存在,当存在的时候就会触发监听
        zooKeeper.exists(path, true);
        //我们发现直接创建,监听不会执行,原因是没有人监听过这个事情
        zooKeeper.create(path, data.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    /**
     * 读取节点数据，并且设置是否监听
     *
     * @param path
     * @param watch
     * @return
     * @throws Exception
     */
    public String readData(String path, boolean watch) throws Exception {
        byte[] data = zooKeeper.getData(path, watch, null);
        return new String(data);
    }

    /**
     * 写入数据
     *
     * @param path
     * @param data
     * @throws Exception
     */
    public void writeData(String path, String data) throws Exception {
        zooKeeper.setData(path, data.getBytes(StandardCharsets.UTF_8), -1);
    }

    /**
     * 获取子节点
     *
     * @param parent
     * @param watch
     * @return
     * @throws Exception
     */
    public List<String> getChildren(String parent, boolean watch) throws Exception {
        return zooKeeper.getChildren(parent, watch);
    }

    /**
     * 监听子节点
     * @param children
     * @param data
     * @throws Exception
     */
    public void createChildren(String children, String data) throws Exception {

        //如果还想知道是哪个子节点创建了,就可以通过这个监听
        zooKeeper.exists(children, true);
        //我们发现直接创建,监听不会执行,原因是没有人监听过这个事情
        zooKeeper.create(children, data.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("ZookeeperWatcher03的process方法执行了");
        Event.KeeperState state = event.getState();
        Event.EventType type = event.getType();
        String path = event.getPath();
        //判断客服端是否处于连接状态
        if (state == Event.KeeperState.SyncConnected) {
            switch (type) {
                case None:
                    System.out.println("连接成功");
                    break;
                //节点创建时
                case NodeCreated:
                    System.out.println("节点创建成功");
                    try {
                        byte[] data = zooKeeper.getData(path, true, null);
                        System.out.println(new String(data));
                    } catch (KeeperException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                //节点改变时
                case NodeDataChanged:
                    System.out.println("数据更新成功");
                    try {
                        byte[] data = zooKeeper.getData(path, true, null);
                        System.out.println(new String(data));
                    } catch (KeeperException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                //字节点发生变化时
                case NodeChildrenChanged:
                    System.out.println("子节点发生了变化");
                    try {
                        //设置返回的是哪个父节点发生了变化
                        List<String> children = zooKeeper.getChildren(path, true);
                        children.forEach(System.out::println);
                    } catch (KeeperException | InterruptedException e) {
                        e.printStackTrace();
                    }
                    break;
                //节点删除时发生变化
                case NodeDeleted:
                    System.out.println("节点删除成功");
                    break;
            }
        }
        countDownLatch.countDown();
    }
}
